<?php

/**
 * This is the model class for table "public.template_content".
 */
require_once(dirname(__FILE__).'/base/TemplateContentBase.php');
class TemplateContent extends TemplateContentBase
{
	public function behaviors()
    {
        return array(
            'timestamp'=>array(
                'class'=>'TimestampBehavior',
            ),
        );
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        return array(
            array('html, log, parent_id', 'required'),
            array('parent_id, log, creation_datetime, last_update, template_id, revision_id, status, css_files, js_files', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, template_id, revision_id, html, creation_datetime, last_update, status, css_files, js_files', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'template' => array(self::BELONGS_TO, 'Template', 'template_id'),
            'parent' => array(self::BELONGS_TO, 'TemplateContent', 'parent_id'),
        );
    }
    
    protected function beforeValidate()
    {
        if (!is_array($this->css_files))
            $this->css_files = array();
        if (count($this->css_files))
        {
            //remove duplicate files
            array_unique($this->css_files);
            $files = array();
            foreach ($this->css_files as $index => $value)
                if (empty($value) === false)
                {
                    //$files[] = str_replace('themes/'.Yii::app()->theme->name.'/styles/', '', $value);
                    if (strpos($value, '/') !== false)
                        $value = substr(strrchr($value, '/'),1);
                    $files[] = $value;
                }
                    
            $this->css_files = $files;
        }
        $this->css_files = var_export($this->css_files, true);
        
        if (!is_array($this->js_files))
            $this->js_files = array();
        if (count($this->js_files))
        {
            //remove duplicate files
            array_unique($this->js_files);
            $files = array();
            foreach ($this->js_files as $index => $value)
                if (empty($value) === false)
                {
                    //$files[] = str_replace('themes/'.Yii::app()->theme->name.'/scripts/', '', $value);
                    if (strpos($value, '/') !== false)
                        $value = substr(strrchr($value, '/'),1);
                    $files[] = $value;
                }
            $this->js_files = $files;
        }
        $this->js_files = var_export($this->js_files, true);
        //$this->parent_id = (int) $this->parent_id;
        
        return parent::beforeValidate();
    }
    
    protected function afterFind()
    {
        if (empty($this->css_files) === false)
            $this->css_files = $this->evaluateExpression($this->css_files);
        if (empty($this->js_files) === false)
            $this->js_files = $this->evaluateExpression($this->js_files);
            
        $dbTime = strtotime($this->last_update);
        $fileTime = 0;
        if (is_object($this->template))
        {
            if (file_exists($this->getViewFile()))
                $fileTime = filemtime($this->getViewFile());
            
            if ($fileTime - $dbTime > 10) //more than 10 secs
                $this->html = file_get_contents($this->getViewFile());
            elseif ($dbTime - $fileTime > 10)
                file_put_contents($this->getViewFile(), $this->html);
        }
        
        parent::afterFind();
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('template_id',$this->template_id);
        $criteria->compare('revision_id',$this->revision_id);
        $criteria->compare('status',$this->status);

        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
            'sort'=>array(
                'defaultOrder'=>'revision_id DESC',
            ),
            'pagination'=>array(
                'pageSize'=>Settings::BO_PAGE_SIZE,
            ),
        ));
    }
    
    protected function afterSave(){
        if (is_object($this->template))
            file_put_contents($this->getViewFile(), $this->html);
        return parent::afterSave();
    }
    
    /**
    * return template content view path that can be used in render(Partial)
    * filename format is template-alias.r####.php
    */
    public function getView() {
        $template = $this->template;
        if (is_object($template))
        {
            if (empty($template->group) || $template->group === 'master')
            {
                return "{$template->alias}.r{$this->revision_id}";
            }
            else
            {
                return "{$template->group}/{$template->alias}.r{$this->revision_id}";
            }
        }
        else
            throw new CException('Not found template id:'.$this->template_id);
    }
    
    /**
    * return absolute path to the view file of template content
    * filename format is template-alias.r####.php
    */
    public function getViewFile() {
        if (is_object($this->template) && $this->template->group === 'master')
        {
            $viewFile = 'layouts/'.$this->View.'.php';
        }
        else
        {
            $viewFile = $this->View.'.php';
        }
        $viewFile = Yii::getPathOfAlias('site').'/../themes/'.Yii::app()->cmsManager->CmsTheme->name.'/views/'.$viewFile;
        if (!file_exists(dirname($viewFile)))
            @mkdir(dirname($viewFile), 0777);
        return $viewFile;
    }
    
    public function ensureViewExist() {
        if (!file_exists($this->getViewFile()))
            file_put_contents($this->getViewFile(), $this->html);
    }
}
